//
//  AppDelegate.m
//  ZXOCWeiBo
//
//  Created by mac on 15/11/28.
//  Copyright © 2015年 itcast. All rights reserved.
//

#import "AppDelegate.h"

#import "ZXTabBarController.h"
#import "ZXNewFeatureController.h"
#import "ZXOAuthController.h"
#import "ZXStatusPhotosVIew.h"


@interface AppDelegate ()

@property(nonatomic,assign)UIBackgroundTaskIdentifier  beforetasKId;

@end

@implementation AppDelegate



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
//    计算图片尺寸
    [ZXStatusPhotosVIew photosSizeWithPicCount:2];
    [ZXStatusPhotosVIew photosSizeWithPicCount:4];
    [ZXStatusPhotosVIew photosSizeWithPicCount:6];
    [ZXStatusPhotosVIew photosSizeWithPicCount:9];
    
    //从Plist中获取版本号
    NSString * currentVersion = [NSUserDefaults VersionFromInfoPlist];
    
    //创建窗口
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    
   
//    从沙盒中取出版本号
 NSString * version = [NSUserDefaults VersionFromSandBox];
    if (version == nil || ![currentVersion isEqualToString:version] )
    {
        //新特性控制器
        ZXNewFeatureController * newcontroller = [[ZXNewFeatureController alloc]init];
        //设置窗口的根控制器
        self.window.rootViewController = newcontroller;
        //将版本号保证在用户偏好设置中
        [NSUserDefaults saveCurrentVersion];
    }
    else
    {
        NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
        if ([defaults objectForKey:@"access_token"] == nil)
        {
            ZXOAuthController * oauthCeontoller = [[ZXOAuthController alloc]init];
            
            UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:oauthCeontoller];
             //设置窗口的根控制器
            self.window.rootViewController = nav;
        }
        else
        {
        //首页控制器
            ZXTabBarController * tabBarcontr = [[ZXTabBarController alloc]init];
            //设置窗口的根控制器
            self.window.rootViewController = tabBarcontr;
        }

    }
    
//    设置法通知权限 只有在IOS 8.0 以上才来执行
    
    if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0)
    {
        UIUserNotificationSettings * settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];
        [application registerUserNotificationSettings:settings];
    }
    
    
    //设置窗口可见
    [self.window makeKeyAndVisible];
    
    return YES;
}
//  程序进入后台会执行
-(void)applicationDidEnterBackground:(UIApplication *)application
{
//    把之前任务结束
    [application endBackgroundTask:self.beforetasKId];
    
    //让程序开始一个后台任务，让NSTimr执行
  UIBackgroundTaskIdentifier tasKId = [application beginBackgroundTaskWithExpirationHandler:^{
//        当任务被停止的时候调用，结束后台任务，释放资源
      [application endBackgroundTask:tasKId];
    }];
    self.beforetasKId = tasKId;
    
}

@end
